package cn.com.callback

import cn.com.kh.KHDBConfig
import cn.com.kh.KHHSTUtil
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.context.ApplicationContext;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.com.kh.getProperty;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import java.time.Instant;
import cn.com.callback.ServiceBackInvoke;

import cn.com.kh.hst.ThreeDesUtil
import com.huasheng.passwordencrypt.DecryptUtil

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.callback
 * @className: apiWebchatLogin
 * @author: HST
 * @description: 马来海外 网聊进线主接口
 * @date: 2023-03-16 10:30
 * @version: 1.0
 */

public class apiWebchatLogin implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWebchatLogin.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        log.debug("-------------------------start apiWebchatLogin-----------------");//获取入参user

        String userid = request.getParameter("userid"); //华盛号
        String language = request.getParameter("language"); //访问语言
        String brand = request.getParameter("brand"); //brand
        //String areaid=request.getParameter("areaid"); //地区 DL大陆 HW海外 HK香港 AM澳门
        //String levelid=request.getParameter("levelid"); //会员等级 1普通 2白银 3黄金 4铂金 5钻石

        // WhatsApp进线时的参数信息
        String whapp_from = request.getParameter("from"); // WhatsApp客户手机
        String whapp_to = request.getParameter("to"); // WhatsApp发送到的账号
        String whapp_clientGuid = request.getParameter("clientGuid"); // WhatsApp发送到的账号

        // 非空保护
        whapp_from = KHUtil.isNull(whapp_from) ? "" : whapp_from;
        whapp_to = KHUtil.isNull(whapp_to) ? "" : whapp_to;
        log.debug("入参userid:" + userid + " 访问语言language：" + language + " brand：" + brand + " from：" + whapp_from + " to：" + whapp_to + " clientGuid：" + whapp_clientGuid);

        //埋点信息  有值进人工 无值则默认机器人排队
        String link = "";
        try {
            //替换中文符号
            brand = brand.replaceAll("“", "\"");
            log.debug("埋点信息-替换中文符号:" + brand);
            JSONObject jsonObject = JSONObject.parseObject(brand);
            link = jsonObject.get("link");

        } catch (Exception e) {
            link = "";
            log.warn("埋点信息-brand转Json对象异常！");
        }
        log.debug("埋点信息-处理后结果link:" + link);

        String areaid, areaname, levelname,password;
        String levelid = "";
        String outData = "";

        String queue = "";

        def type = "yyyy-MM-dd";
        def date = Util.getNowString(type);
        def cname = "SELITE";
        def customerguid, string9;

        log.debug("userid:" + userid);

        // 调用doWhatsAppMain检查处理,如果是WhatsApp进线子方法处理完成后直接返回,如果处理异常会返回userid默认常规调用
        JSONObject ws_ChatResult = doWhatsAppMain(eliteBean, jt, userid, whapp_from, whapp_to);
        log.debug("WhatsApp 进线逻辑处理结果:" + ws_ChatResult.toString());

        String ws_state = ws_ChatResult.getString("state");
        if (ws_state == "1") {
            return ws_ChatResult;
        } else if (ws_state == "0" && (KHUtil.isNull(userid) || userid == "undefined")) {
            userid = ws_ChatResult.getString("userid"); ;
            language = "en";
            log.debug("WhatsApp 进线逻辑处理结束:" + userid);
        }

        //判断是否传userid。判断是否在customer表里能匹配到userid。如果能匹配到，就获取登录；如果匹配不到，就insert customer表
        if (userid != null && userid != "null" && userid != "undefined" && !userid.equals("")) {

            // 查询数据库中是否有该userid
            def selectopenSql = "Select Count(Distinct c.Customer_Guid) As countopenguid From Customer c Where Stringfield9 = ?";
            log.debug("查询数据库中是否有该userid SQL:" + selectopenSql);
            def countopensql = jt.queryForList(selectopenSql, userid);
            log.debug("查询数据库中是否有该userid Result:" + countopensql);
            def map1 = countopensql[0];
            def countopenguid = map1.get("countopenguid");
            log.debug("判断客户customer_guid是否存在。不存在时新增；存在时查询 数量:" + countopenguid);

            ///* 无会员等级接口权限 默认不调度，采用分析是否传华盛号，传则会员
            //判断本地是否有客户，无则新增
            if (countopenguid == 0 || countopenguid.equals("0")) {
                log.debug("不存在userid，新增customer表");
                def openguid1 = Util.getGuid();

                def custname = "Livechat user " + userid;
                log.debug("openguid1:" + openguid1);
                def insertopenSql = "INSERT INTO customer (customer_guid,CUSTOMER_ID,stringfield9,createddate,createdby,MODIFIEDDATE,MODIFIEDBY,customername,customerlevel,sq_15,sq_13,sq_14,CUSTOMERID2)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
                def insertopenSqlResult = jt.update(insertopenSql, openguid1, userid, userid, date, cname, date, cname, custname, levelid, areaid, areaname, levelname, userid);
                log.debug("insertopenSql" + insertopenSql);
                log.debug("insertopenSqlResult" + insertopenSqlResult);
                log.debug("customer表新增客户userid成功");

                JSONObject jsonopenALL2 = new JSONObject();
                jsonopenALL2.put("state", "1");
                jsonopenALL2.put("success", "true");
                //兜底英文队列 新增马来语队列
                if (language == "en") {// 英文
                    queue = 4;//English queue 英语队列
                }else if (language == "mas") {
                    queue = 3;//Malaysian queue 马来语队列
                }else if (language == "zh_cn" ) {
                    queue = 1;//Simplified  Chinese queue 简体队列
                }else if (language == "zh_hk") {
                    queue = 2;//Traditional Chinese queue 简体高级队列
                }else {
                    queue = 4;//English queue 英语队列
                }

                jsonopenALL2.put("queue", queue);
                jsonopenALL2.put("msg", "接口调用成功......");
                log.debug("获取loginname和password");
                JSONObject jsonopen1 = new JSONObject();
                jsonopen1.put("loginName", userid);
                jsonopen1.put("password", "");
                jsonopenALL2.put("result", jsonopen1);
                return jsonopenALL2;

            } else {
                //如存在则查询队员客户的信息
                def selectcustSql = "Select customerlevel, sq_15, sq_13, sq_14,Stringfield11,CUSTOMERID2 From Customer c Where Stringfield9 = ?";
                log.debug("selectopenSql" + selectopenSql);
                def custresultsql = jt.queryForList(selectcustSql, userid);
                log.debug("custresultsql" + custresultsql);
                def map2 = custresultsql[0];
                levelid = map2.get("customerlevel");
                areaid = map2.get("sq_15");
                areaname = map2.get("sq_13");
                levelname = map2.get("sq_14");
                password = map2.get("Stringfield11");
                def CUSTOMERID2 = map2.get("CUSTOMERID2");
                log.debug("levelid:" + levelid + "	,areaid:" + areaid + "	,areaname:" + areaname + "	,levelname:" + levelname+ "	,password:" + password+ "	,CUSTOMERID2:" + CUSTOMERID2);

                //null判定
                if (levelid == null || levelid.equals("")) {
                    levelid = "0";
                }
                //处理黑名单拉黑的CUSTOMERID2更新
                if (CUSTOMERID2 == null || CUSTOMERID2.equals("")) {
                    def updateuserid = "update customer set CUSTOMERID2=? where stringfield9 =?";
                    def updateuseridresult = jt.update(updateuserid, userid, userid);
                    log.debug("updateuserid" + updateuserid);
                    log.debug("updateuseridresult" + updateuseridresult);
                    log.debug("customer表修改客户CUSTOMERID2成功");
                }

                //返回成功的查询结果
                JSONObject jsonALL3 = new JSONObject();
                jsonALL3.put("state", "1");
                jsonALL3.put("success", "true");

                log.debug("levelid:" + levelid);
                //查询数据库中语言、会员等级匹配的队列queueid
                //queue = getqueueid(userid, language, levelid, link, jt);

                //兜底英文队列 新增马来语队列
                if (language == "en") {// 英文
                    queue = 4;//English queue 英语队列
                }else if (language == "mas") {
                    queue = 3;//Malaysian queue 马来语队列
                }else if (language == "zh_cn" ) {
                    queue = 1;//Simplified  Chinese queue 简体队列
                }else if (language == "zh_hk") {
                    queue = 2;//Traditional Chinese queue 简体高级队列
                }else {
                    queue = 4;//English queue 英语队列
                }

                jsonALL3.put("queue", queue);
                jsonALL3.put("msg", "接口调用成功......");
                JSONObject json2 = new JSONObject();
                json2.put("loginName", userid);
                json2.put("password", password);
                jsonALL3.put("result", json2);
                return jsonALL3;
            }


        } else {
            //兜底英文队列 新增马来语队列
            if (language == "en") {// 英文
                queue = 4;//English queue 英语队列
            }else if (language == "mas") {
                queue = 3;//Malaysian queue 马来语队列
            }else if (language == "zh_cn" ) {
                queue = 1;//Simplified  Chinese queue 简体队列
            }else if (language == "zh_hk") {
                queue = 2;//Traditional Chinese queue 简体高级队列
            }else {
                queue = 4;//English queue 英语队列
            }

            //返回失败的结果
            JSONObject jsonALL1 = new JSONObject();
            jsonALL1.put("queue", queue);
            jsonALL1.put("state", "0");
            jsonALL1.put("success", "false");
            jsonALL1.put("msg", "接口调用失败,入参匹配不到相应客户......");
            return jsonALL1;
        }

    }

    // 调用华盛客户信息接口获取信息
    public static String Querypromocode(String injson) {

        long startTime = System.currentTimeMillis();
        log.debug("调用华盛客户信息接口-处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL + "/customer/query-ext";
            log.debug("调用华盛客户信息接口-doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("调用华盛客户信息接口-getResult:" + getResult);

            //解析返回信息
            JSONObject jsonObject = JSONObject.parseObject(getResult, Feature.OrderedField);
            String code = jsonObject.get("code");

            log.debug("调用华盛客户信息接口-code:" + code);
            if (code == "00000") {
                reJson = getResult;
            } else {
                String msg = jsonObject.get("msg");
                reJson = "{\"code\":\"-1\",\"result\":\"用户会员等级、地区获取失败(" + msg + ")\"}";
            }

        } catch (Exception e) {
            log.error("调用华盛客户信息接口-接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"code\":\"-1\",\"result\":\"接口异常\"}";
        }
        return reJson;
    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }

    /**
     * @param str :
     * @return String 用户号
     * @author LiJT
     * @description WhatsApp进线客户处理逻辑
     * @date 2023-01-28 17:10
     */
    public static JSONObject doWhatsAppMain(EliteBean eliteBean, JdbcTemplate jt, String in_UserID, String whapp_from, String whapp_to) {

        // 初始化返回参数
        JSONObject chatResult = new JSONObject();
        chatResult.put("state", "1");
        chatResult.put("success", "true");

        // 检查是否是WhatsApp进线(WhatsApp的进线需要From和To都不为空)
        if (!KHUtil.isNull(whapp_to) && !KHUtil.isNull(whapp_from)) {
            String selectType = "";
            // 处理WhatsApp进线号码国际号码区号
            String whapp_to_enc = KHHSTUtil.getPhoneNo(eliteBean, whapp_to); // WhatsApp账号去除前缀
            String whapp_to_type = whapp_to.startsWith("+") ? "+" : "00"; // WhatsApp账号类别识别
            String mobile_enc;
            try{
                mobile_enc = DecryptUtil.encrypt(whapp_to_enc);
            } catch (Exception e) {
                log.error("mobile加密处理异常" + e.getMessage());
                mobile_enc = "";
            }
            log.debug("WhatsApp客户手机号码处理-去除前缀:" + whapp_to_enc + " 类别识别:" + whapp_to_type+ " mobile加密处理:" + mobile_enc);

            // 检查当前进线的WhatsApp账号 是否有 存在客户
            List<Map<String, Object>> selectCustResult = new ArrayList<>();
            String selectLangSQL = '''Select R2.Customer_Guid,
                                       R2.Customer_Id,
                                       R2.Stringfield9,
                                       Case
                                         When R2.Mobile_enc = ? Then
                                          'MOBILE'
                                         Else
                                          ''
                                       End As Selecttype,CREATEDDATE,
                                     Case
                                       When R2.Open_Id = ? Then
                                        1
                                       When R2.Webchat_Target_Id = ? Then
                                        2
                                       When R2.Open_Id Like Concat('%', ?) Then
                                        3
                                       When R2.Webchat_Target_Id Like Concat('%', ?) Then
                                        4
                                       When R2.Mobile_enc = ? Then
                                        5
                                       Else
                                        99
                                     End As selectLevel
                                  From Customer R2
                                 Where 1 = 1
                                   And (R2.Open_Id = ? Or R2.Open_Id Like Concat('%', ?) Or R2.Webchat_Target_Id = ? Or
                                       R2.Webchat_Target_Id Like Concat('%', ?) Or R2.mobile_enc = ?) Order By 5,6 Limit 1''';
            selectCustResult = jt.queryForList(selectLangSQL, mobile_enc, whapp_to, whapp_to, whapp_to_enc, whapp_to_enc, mobile_enc, whapp_to, whapp_to_enc, whapp_to, whapp_to_enc, mobile_enc);
            log.debug("检查当前客户信息是否存在:" + selectCustResult.toString());

            //解析当前匹配查询的客户customer_guid
            String ob_Customer_Guid;
            if(selectCustResult.size()>0){
                ob_Customer_Guid = selectCustResult.get(0).get("Customer_Guid").toString();
            }else{
                ob_Customer_Guid="";
            }
            log.debug("ob_Customer_Guid:" + ob_Customer_Guid);

            // 检查发送账号是否是服顾账号
            List<Map<String, Object>> selectFGResult = new ArrayList<>();
            String selectFGSQL;
            //判断是否是营销队列 还是WhatsApp队列
            if(KHDBConfig.getParamConfig(eliteBean,"WhatsAppYX").contains(whapp_from)){
                selectFGSQL = '''Select R1.Staff_Id, R1.Staffname From Staff R1 Where R1.Ewu_Id = ?''';
                selectFGResult = jt.queryForList(selectFGSQL, whapp_from);
            }else{
                selectFGSQL = '''select ob.Handleby_Id as Staff_Id from objective ob where 1=1 and ob.MAP_ID= ? and ob.customer_guid= ? and ob.Handleby_Id is not null and ob.Handleby_Id!='' and ob.Handleby_Id in (select R1.Staff_Id From Staff R1 Where R1.Ewu_Id = ?)''';
                selectFGResult = jt.queryForList(selectFGSQL, "MY48ZX", ob_Customer_Guid, whapp_from);
            }
            log.debug("检查发送账号是否是服顾账号:" + selectFGResult.toString());

            // 根据进线账号控制逻辑
            if (selectFGResult.size() == 0) {
                // 客服账号
                if (selectCustResult.size() == 0) {
                    // 客户信息不存在-新增
                    String re_Customer_Guid = "WHATSAPP_" + KHUtil.getRandomString(27);
                    String re_StringField9 = whapp_to;
                    selectType = "";
                    log.debug("WhatsApp匹配内部客户的方式:" + selectType);

                    String insertCustSQL = '''Insert Into Customer
                                                  (Customer_Guid,
                                                   Customer_Id,
                                                   Stringfield9,
                                                   Createddate,
                                                   Createdby,
                                                   Modifieddate,
                                                   Modifiedby,
                                                   Customername,
                                                   Customerlevel,
                                                   Sq_15,
                                                   Sq_13,
                                                   Sq_14,Icon_Url,Open_Id,Webchat_Target_Id,OTHERS)
                                                Values
                                                  (?, ?, ?, Now(), ?, Now(), ?, ?, ?, ?, ?, ?,'/ngs/js/plugins/chat/images/whatsapp.png',?,?,?)''';
                    int insertCust = jt.update(insertCustSQL, re_Customer_Guid, "", re_StringField9, "SELITE", "SELITE", whapp_to, "", "", "", "", whapp_to, whapp_to,whapp_to_enc);
                    log.debug("新增本地对应客户WhatsApp信息 DB操作数量:" + insertCust);

                    chatResult.put("queue", 4);
                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to);
                    chatResult.put("msg", "接口调用成功(WhatsApp客服账号-新增)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                } else {
                    // 客户信息存在-查询
                    String re_Customer_Guid = selectCustResult.get(0).get("Customer_Guid").toString();
                    String re_StringField9 = selectCustResult.get(0).get("Stringfield9").toString();
                    selectType = selectCustResult.get(0).get("selectType").toString();
                    log.debug("re_Customer_Guid:"+re_Customer_Guid+"    re_StringField9:"+re_StringField9+" WhatsApp匹配内部客户的方式:" + selectType);

                    String updateCustSQL = '''Update Customer
                                           Set Icon_Url = '/ngs/js/plugins/chat/images/whatsapp.png',
                                               Open_Id = Case
                                                           When ('MOBILE' = ? And '00' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                            Replace(?, '+', '00')
                                                           Else
                                                            Open_Id
                                                         End,
                                               Webchat_Target_Id = Case
                                                                     When ('MOBILE' = ? And '+' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                                      ?
                                                                     Else
                                                                      Webchat_Target_Id
                                                                   End,OTHERS= ? 
                                         Where Customer_Guid = ?''';
                    int updateCust = jt.update(updateCustSQL, selectType, whapp_to_type, whapp_to, selectType, whapp_to_type, whapp_to, whapp_to_enc, re_Customer_Guid);
                    log.debug("更新本地对应客户WhatsApp信息 DB操作数量:" + updateCust);

                    chatResult.put("queue", 4);
                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to.replace("+","00"));
                    chatResult.put("msg", "接口调用成功(WhatsApp客服账号-更新)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                }

            } else {
                // 服顾账号
                String re_Staff_Id = selectFGResult.get(0).get("Staff_Id").toString();
                if (selectCustResult.size() == 0) {//只有营销队列且客户不存在的此类场景（有staff维护归属WhatsApp 但是 客户不存在） 会进入，则新增客户关系。
                    // 客户信息不存在-新增
                    String re_Customer_Guid = "WHATSAPP_" + KHUtil.getRandomString(27);
                    String re_StringField9 = whapp_to;
                    selectType = "";
                    log.debug("WhatsApp匹配内部客户的方式:" + selectType);

                    String insertCustSQL = '''Insert Into Customer
                                                  (Customer_Guid,
                                                   Customer_Id,
                                                   Stringfield9,
                                                   Createddate,
                                                   Createdby,
                                                   Modifieddate,
                                                   Modifiedby,
                                                   Customername,
                                                   Customerlevel,
                                                   Sq_15,
                                                   Sq_13,
                                                   Sq_14,Icon_Url,Open_Id,Webchat_Target_Id,OTHERS)
                                                Values
                                                  (?, ?, ?, Now(), ?, Now(), ?, ?, ?, ?, ?, ?,'/ngs/js/plugins/chat/images/whatsapp.png',?,?,?)''';
                    int insertCust = jt.update(insertCustSQL, re_Customer_Guid, "", re_StringField9, "SELITE", "SELITE", whapp_to, "", "", "", "", whapp_to, whapp_to,whapp_to_enc);
                    log.debug("新增本地对应客户WhatsApp信息 DB操作数量:" + insertCust);
/*
                    String insertRouteSQL = '''Insert Into Chat_Multichannel_Route
                                      (Route_Guid,
                                       Customer_Guid,
                                       Openid,
                                       Ownerstaff_Id,
                                       Curvisitchannel,
                                       Firstvisittime,
                                       Curvisittime,
                                       Bind_Status,
                                       Lastupdateinfotime,
                                       Ower_Id)
                                    Values
                                      (Uuid(), ?, ?, ?, 'WC', Now(), Now(), 1, Now(), ?)''';
                    int insertRoute = jt.update(insertRouteSQL, re_Customer_Guid, "", re_Staff_Id, whapp_from);
                    log.debug("新增本地对应客户WhatsApp路由信息 DB操作数量:" + insertRoute);

                    //20230901-新增逻辑 匹配对应 whatsapp 营销账号进入 whatsapp 营销队列
                    if(KHDBConfig.getParamConfig(eliteBean,"WhatsAppYX").contains(whapp_from)){
                        chatResult.put("queue", 20);
                    }else{
                        chatResult.put("queue", 15);
                    }
*/
                    chatResult.put("queue", 20);
                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to);
                    chatResult.put("msg", "接口调用成功(WhatsApp服顾账号-新增)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                } else {
                    // 客户信息存在-查询 顾问模式进入 兼容 一个WhatsApp账号多人使用的场景 注：此刻的路由表 Chat_Multichannel_Route 必须有且仅有一条
                    String re_Customer_Guid = selectCustResult.get(0).get("Customer_Guid").toString();
                    String re_StringField9 = selectCustResult.get(0).get("Stringfield9").toString();
                    selectType = selectCustResult.get(0).get("selectType").toString();
                    log.debug("re_Customer_Guid:"+re_Customer_Guid+"    re_StringField9:"+re_StringField9+" WhatsApp匹配内部客户的方式:" + selectType);

                    //进行路由表清理 保证路由表数据有且仅唯一
                    String deleteRouteSQL = '''delete
                                                  From Chat_Multichannel_Route
                                                 Where Customer_Guid = ?
                                                   And Ownerstaff_Id != ?
                                                   And Bind_Status = 1''';
                    int deleteRoute = jt.update(deleteRouteSQL, re_Customer_Guid, re_Staff_Id);
                    log.debug("检查专属客户信息路由表几条存在:" + deleteRoute);

                    // 服顾账号&客户信息存在-检查专属客户信息表是否存在
                    String selectRouteSQL = '''Select Route_Guid
                                                  From Chat_Multichannel_Route
                                                 Where Customer_Guid = ?
                                                   And Ownerstaff_Id = ?
                                                   And Bind_Status = 1''';
                    List<Map<String, Object>> selectRouteResult = jt.queryForList(selectRouteSQL, re_Customer_Guid, re_Staff_Id);
                    log.debug("检查专属客户信息路由表是否存在:" + selectRouteResult.toString());

                    //判断如路由表不存在则新增 前提是 非营销队列 则新增
                    if (selectRouteResult.size() == 0&&!KHDBConfig.getParamConfig(eliteBean,"WhatsAppYX").contains(whapp_from)) {
                        // 检查专属客户信息表不存在-新增
                        String Route_Guid = KHUtil.getRandomString(36);
                        String insertRouteSQL = '''Insert Into Chat_Multichannel_Route
                                      (Route_Guid,
                                       Customer_Guid,
                                       Openid,
                                       Ownerstaff_Id,
                                       Curvisitchannel,
                                       Firstvisittime,
                                       Curvisittime,
                                       Bind_Status,
                                       Lastupdateinfotime,
                                       Ower_Id)
                                    Values
                                      (?, ?, ?, ?, 'WC', Now(), Now(), 1, Now(), ?)''';
                        int insertRoute = jt.update(insertRouteSQL, Route_Guid, re_Customer_Guid, "", re_Staff_Id, whapp_from);
                        log.debug("新增本地对应客户WhatsApp路由信息 DB操作数量:" + insertRoute + " Route_Guid:" + Route_Guid);
                    }

                    String updateCustSQL = '''Update Customer
                                           Set Icon_Url = '/ngs/js/plugins/chat/images/whatsapp.png',
                                               Open_Id = Case
                                                           When ('MOBILE' = ? And '00' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                            Replace(?, '+', '00')
                                                           Else
                                                            Open_Id
                                                         End,
                                               Webchat_Target_Id = Case
                                                                     When ('MOBILE' = ? And '+' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                                      ?
                                                                     Else
                                                                      Webchat_Target_Id
                                                                   End,OTHERS= ? 
                                         Where Customer_Guid = ?''';
                    int updateCust = jt.update(updateCustSQL, selectType, whapp_to_type, whapp_to, selectType, whapp_to_type, whapp_to, whapp_to_enc, re_Customer_Guid);
                    log.debug("更新本地对应客户WhatsApp信息 DB操作数量:" + updateCust);

                    //20230901-新增逻辑 匹配对应 whatsapp 测试账号进入 whatsapp 生产队列 00601155595338  测试 0085254967168
                    def tempqueue;
                    //检查对于whatsapp对立的队列是否存在活跃会话，存在则按临时客户处理。不存在咋按当前
                    if(KHDBConfig.getParamConfig(eliteBean,"WhatsAppYX").contains(whapp_from)){
                        chatResult.put("queue", 20);
                        /*
                            如营销队列 则直接获取备用客户
                            新增一条customer数据，作为临时客户数据，对应额外需处理字段如上：
                            父customer_guid   客户whatsapp账号  客户给谁（那个顾问）的whatsapp账号存储，
                            stringfield9字段特殊处理账号，涉及唯一性，customer其他数据新增字段一致 返回临时客户的 stringfield9 给到网聊
                        */
                        log.debug("判断当前客户进线营销队列!");

                        //检查当前客户 是否已经在营销队列中  在则返回当前customer_guid
                        String selecttempcustSQL = '''select cr.client_id as customer_guid from chat_request cr 
                                                            left join chat_session cs  
                                                            on cs.id=cr.chat_session_id  and  cs.client_id=cr.client_id 
                                                            where 1=1 
                                                            and cr.client_id=? and cr.brand ='WhatsApp' and cr.queue_id=20
                                                            and cs.client_id=? and cs.perm_flag=0 and cs.end_time is null''';
                        List<Map<String, Object>> selecttempcustResult = jt.queryForList(selecttempcustSQL, re_Customer_Guid, re_Customer_Guid);
                        log.debug("检查当前客户是否已经存在未结束的whatsapp的营销会话:" + selecttempcustResult.toString());

                        //如不存在，则处理
                        if (selecttempcustResult.size() == 0) {
                            log.debug("不存在未结束的whatsapp的营销会话！" );
                            //检查当前临时客户是否已经新增过 如新增过 则直接拿副customer_guid
                            selecttempcustSQL = '''select customer_guid,Stringfield9 from customer where 1=1 and STRINGFIELD106=? ''';
                            //String selecttempcustSQL = '''select STRINGFIELD106 as customer_guid,Stringfield9 from customer where 1=1 and customer_guid=? and STRINGFIELD106 is not null''';
                            selecttempcustResult = jt.queryForList(selecttempcustSQL, re_Customer_Guid);
                            log.debug("检查当前客户是否新增过:" + selecttempcustResult.toString());

                        }else{//如存在，则不处理
                            log.debug("存在未结束的whatsapp的营销会话！" );
                        }

                        //如不存在，则不处理
                        if (selecttempcustResult.size() == 0) {
                            // 客户信息-新增临时客户
                            String temp_Customer_Guid = "WHATSAPP_" + KHUtil.getRandomString(27);
                            String temp_StringField9 = whapp_to+"_" + KHUtil.getRandomString(6);
                            log.debug("temp_Customer_Guid:" + temp_Customer_Guid+"  ,temp_StringField9:" + temp_StringField9);

                            String insertCustSQL = '''Insert Into Customer
                                                  (Customer_Guid,
                                                   Customer_Id,
                                                   Stringfield9,
                                                   Createddate,
                                                   Createdby,
                                                   Modifieddate,
                                                   Modifiedby,
                                                   Customername,
                                                   Customerlevel,
                                                   Sq_15,
                                                   Sq_13,
                                                   Sq_14,Icon_Url,Open_Id,Webchat_Target_Id,OTHERS,STRINGFIELD106,STRINGFIELD107)
                                                Values
                                                  (?, ?, ?, Now(), ?, Now(), ?, ?, ?, ?, ?, ?,'/ngs/js/plugins/chat/images/whatsapp.png',?,?,?,?,?)''';
                            int insertCust = jt.update(insertCustSQL, temp_Customer_Guid, "", temp_StringField9, "SELITE", "SELITE", whapp_to, "", "", "", "", whapp_to, whapp_to,whapp_to_enc,re_Customer_Guid,whapp_from);
                            log.debug("新增本地对应临时客户WhatsApp信息 DB操作数量:" + insertCust);

                            //传值处理，复当前temp客户的id 给到chat
                            re_Customer_Guid=temp_Customer_Guid;
                            re_StringField9=temp_StringField9;
                        }else{
                            log.debug("temp客户已经存在！" );
                            //传值处理，复当前temp客户的id 给到chat
                            re_Customer_Guid=selecttempcustResult.get(0).get("customer_guid").toString();;
                            re_StringField9=selecttempcustResult.get(0).get("Stringfield9").toString();;
                        }
                    }else{
                        chatResult.put("queue", 15);
                    }
                    log.debug("re_Customer_Guid："+re_Customer_Guid+"    re_StringField9："+re_StringField9 );

                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to.replace("+","00"));
                    chatResult.put("msg", "接口调用成功(WhatsApp服顾账号-更新)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                }
            }

        } else {
            String whapp_to_enc = KHHSTUtil.getPhoneNo(eliteBean, whapp_to); // WhatsApp账号去除前缀
            String mobile_enc;
            try{
                mobile_enc = DecryptUtil.encrypt(whapp_to_enc);
            } catch (Exception e) {
                log.error("mobile加密处理异常" + e.getMessage());
                mobile_enc = "";
            }

            // 进线如果不存在UserID则通过进线号码查询一下
            if (KHUtil.isNull(in_UserID) && !KHUtil.isNull(whapp_to)) {
                String selectLangSQL = '''Select R2.Customer_Guid,
                                       R2.Customer_Id,
                                       R2.Stringfield9,
                                       Case
                                         When R2.Mobile_enc = ? Then
                                          'MOBILE'
                                         Else
                                          ''
                                       End As Selecttype
                                  From Customer R2
                                 Where 1 = 1
                                   And (R2.Open_Id = ? Or R2.Open_Id Like Concat('%', ?) Or R2.Webchat_Target_Id = ? Or
                                       R2.Webchat_Target_Id Like Concat('%', ?) Or R2.Mobile_enc = ?) Limit 1''';
                List<Map<String, Object>> selectCustResult = jt.queryForList(selectLangSQL, mobile_enc, whapp_to, whapp_to_enc, whapp_to, whapp_to_enc, mobile_enc);
                log.debug("非WhatsApp进线-检查当前客户信息是否存在:" + selectCustResult.toString());

                if (selectCustResult.size() > 0) {
                    String re_UserID = selectCustResult.get(0).get("Stringfield9").toString();

                    chatResult.put("state", "0");
                    chatResult.put("userid", re_UserID);
                    chatResult.put("msg", "非WhatsApp进线-查询到本地UserID-" + re_UserID);

                } else {
                    chatResult.put("state", "-1");
                    chatResult.put("msg", "非WhatsApp进线-未查询到本地UserID");

                }

            } else {
                chatResult.put("state", "-2");
                chatResult.put("msg", "非WhatsApp进线-不满足查询本地账号");

            }
            log.debug("非WhatsApp进线-处理客户信息结果:" + chatResult.toString());
        }
        return chatResult;

    }
}